﻿using System;
using System.Web.Services;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.EntityModel;
using Resources;

namespace MonkeyWarranty.Web.WarrantyTickets
{
    public partial class SendToSupplier : System.Web.UI.Page
    {
        #region Properties

        private static WarrantyProductBiz _warrantyProductBiz;
        private static WarrantyProductBiz WarrantyProductManager
        {
            get { return _warrantyProductBiz ?? (_warrantyProductBiz = new WarrantyProductBiz()); }
        }

        private static SupplierBiz _supplierBiz;

        private static SupplierBiz SupplierManager
        {
            get { return _supplierBiz ?? (_supplierBiz = new SupplierBiz()); }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var groups = SupplierManager.GetAllSupplierGroups();
                groups.Insert(0, new SupplierGroup { Id = 0, Name = Resources.GlobalStrings.AllGroups });

                ddlSupplierGroups.DataTextField = "Name";
                ddlSupplierGroups.DataValueField = "Id";
                ddlSupplierGroups.DataSource = groups;
                ddlSupplierGroups.DataBind();
            }
        }

        #region Webmethods

        [WebMethod(EnableSession = true)]
        public static object GetWarrantyProduct(int id)
        {
            var dateFormat = "{0:" + GlobalStrings.DateFormat + "}";
            var product = WarrantyProductManager.GetWarrantyTicketProductView(id);
            if (product != null)
            {
                product.SentDateString = string.Format(dateFormat, product.SentDate ?? DateTime.Today);
                product.WishDateString = string.Format(dateFormat, product.WishDate ?? DateTime.Today.AddDays(7));
            }
            return product;
        }

        [WebMethod(EnableSession = true)]
        public static object SearchSuppliers(string name, int supplierGroupId, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            var supplierCount = SupplierManager.CountSuppliers(name, supplierGroupId);
            var suppliers = SupplierManager.SearchSuppliers(name, supplierGroupId, jtStartIndex, jtPageSize, jtSorting);
            return new { Result = "OK", Records = suppliers, TotalRecordCount = supplierCount };
        }

        [WebMethod(EnableSession = true)]
        public static object SendProductToSupplier(long id, int supplierId, string note, string sentDate, string wishDate)
        {
            WarrantyProductManager.SendToSupplier(id, supplierId, note, sentDate, wishDate, GlobalStrings.DateFormat);
            return new {Result = "OK"};
        }

        #endregion
    }
}